(function () {
    var exports = this;

    var $ = null;

    var loadPackageInfo = function () {
        window.packageName = cc.sys.isNative ? jsb.reflection.callStaticMethod.apply(jsb.reflection, {
                iOS: ["AppController", "getBundleId"],
                Android: ["org/cocos2dx/javascript/AppActivity", "getBundleId", "()Ljava/lang/String;"]
            }[cc.sys.os]) : "";
        window.packageUri = packageName.split('.').join('/');
        window.udid = cc.sys.isNative ? jsb.reflection.callStaticMethod.apply(jsb.reflection, {
                iOS: ["AppController", "getUdid"],
                Android: [packageUri + '/Global', "getUdid", "()Ljava/lang/String;"]
            }[cc.sys.os]) : "0123456789abcdef";
        window.nativeVersion = cc.sys.isNative ? jsb.reflection.callStaticMethod.apply(jsb.reflection, {
                iOS: ["AppController", "getVersionName"],
                Android: [packageUri + '/Global', "getVersionName", "()Ljava/lang/String;"]
            }[cc.sys.os]) : "0.0.0";
    };

    var restoreSavedVolume = function () {
        if (_.isEmpty(cc.sys.localStorage.getItem('yinxiaoPrecent')))
            cc.sys.localStorage.setItem('yinxiaoPrecent', 100);
        if (_.isEmpty(cc.sys.localStorage.getItem('yinyuePrecent')))
            cc.sys.localStorage.setItem('yinyuePrecent', 100);
        // var yinxiaoPrecent = cc.sys.localStorage.getItem('yinxiaoPrecent');
        // var yinyuePrecent = cc.sys.localStorage.getItem('yinyuePrecent');
        // cc.audioEngine.setEffectsVolume(yinxiaoPrecent / 100);
        // cc.audioEngine.setMusicVolume(yinyuePrecent / 100);
    };

    var keepScreenOn = function () {
        if (cc.sys.isNative && cc.Device && cc.Device.setKeepScreenOn)
            cc.Device.setKeepScreenOn(true);
    };


    var UpdateScene = cc.Scene.extend({
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
        },
        ctor: function () {
            this._super();
            if (!window.firstUpdate) {
                loadPackageInfo();
                keepScreenOn();
                restoreSavedVolume();
                if (_.isFunction(beginNetListener)) {
                    beginNetListener();
                }

                if (cc.sys.isNative && cc.Device && cc.Device.setKeepScreenOn)
                    cc.Device.setKeepScreenOn(true);

                var funcBak = (cc.sys.isNative ? ccui.Text.prototype._ctor : ccui.Text.prototype.ctor);
                ccui.Text.prototype.setFontRes = function (fontRes) {
                    var path = fontRes;
                    var fontName = '';
                    if (path != null) {
                        if (cc.sys.isNative) {
                            fontName = path;
                        } else {
                            fontName = path.substr(4).match(/([^\/]+)\.(\S+)/);
                            fontName = fontName ? fontName[1] : "";
                        }
                        this.setFontName(fontName);
                        //this.enableOutline(cc.color(0, 0, 0), 2);
                    }
                };
                // var func = function (textContent, fontName, fontSize) {
                //     funcBak.call(this, textContent, fontName, fontSize);
                //     this.setFontRes(res.default_ttf);
                // };
                var func = function (textContent, _fontName, fontSize) {
                    if (!fontSize) {
                        var path = res.default_ttf;
                        var fontName = '';
                        if (path != null) {
                            if (cc.sys.isNative) {
                                fontName = path;
                            } else {
                                fontName = path.substr(4).match(/([^\/]+)\.(\S+)/);
                                fontName = fontName ? fontName[1] : "";
                            }
                        }
                        // console.log('xxx ' + _fontName + ' ' + fontName);
                        funcBak.call(this, textContent || '', fontName, fontSize || 0);
                    }
                    else
                        funcBak.call(this, textContent || '', _fontName, fontSize || 0);
                };
                if (cc.sys.isNative)
                    ccui.Text.prototype._ctor = func;
                else
                    ccui.Text.prototype.ctor = func;

                window.firstUpdate = true;
            }

        },
        run: function () {
            var that = this;

            var scene = ccs.load(res.LoginLayer_json, "res/");
            this.addChild(scene.node);
            $ = create$(this.getChildByName("Layer"));

            if (cc.sys.isNative) {
                var save_native_version = cc.sys.localStorage.getItem('save_native_version');
                if (!save_native_version || save_native_version != window.nativeVersion) {
                    jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "project.manifest");
                    jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "project.manifest.tmp");
                    jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "version.manifest");
                    jsb.fileUtils.removeFile(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "version.manifest.tmp");
                    jsb.fileUtils.removeDirectory(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "res");
                    jsb.fileUtils.removeDirectory(jsb.fileUtils.getWritablePath() + (cc.sys.os == cc.sys.OS_IOS ? "/storage/" : "/") + "src");
                }
            }

             if (false) {
            // if (cc.sys.isNative) {  // 热更新
                var progressLabel = $('progress_label');
                var progressBg = $('progress_bg');
                var progressBar = $('progress_bg.progress');

                progressLabel.setVisible(true);
                progressBg.setVisible(false);

                progressLabel.setString("正在请求服务器....");

                var manifestUrl = "res/project.manifest";
                if (!jsb.fileUtils.isFileExist(manifestUrl)) {
                    cc.error("manifestUrl is null!!!");
                    alert1("manifestUrl is null!!!");
                }
                //var manifestUrl = "res/project" + (cc.sys.os == cc.sys.OS_IOS ? "-ios" : "") + ".manifest";
                //var manifestUrl = "res/project-debug.manifest";
                var storagePath = cc.sys.writablePath;
                var manager = new jsb.AssetsManager(manifestUrl, storagePath);

                window.curVersion = manager.getLocalManifest().getVersion();
                $('lb_version').setString(window.curVersion);

                manager.retain();
                manager.update();

                var retainCnt = 1;

                if (!manager.getLocalManifest().isLoaded()) {
                    cc.log("Fail to update assets, step skipped.");

                    if (--retainCnt >= 0)
                        manager.release();

                    this.loadGame();
                }
                else {
                    var listener = new jsb.EventListenerAssetsManager(manager, function (event) {
                        switch (event.getEventCode()) {
                            case jsb.EventAssetsManager.NEW_VERSION_FOUND:
                                progressLabel.setString("正在更新图片资源..");
                                progressBg.setVisible(true);
                                cc.log("New version found.");
                                break;
                            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
                                cc.log("No local manifest file found, skip assets update.");
                                break;
                            case jsb.EventAssetsManager.UPDATE_PROGRESSION:
                                var percent = event.getPercent();
                                var filePercent = event.getPercentByFile();
                                progressBar.setPercent(percent);
                                cc.log("Download percent : " + percent + " | File percent : " + filePercent);
                                break;
                            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
                            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
                                if (!_.isFunction(isNetwork) || isNetwork()) {
                                    var str = '未找到更新文件，正在进入游戏';
                                    progressLabel.setString(str);
                                    if (--retainCnt >= 0)
                                        manager.release();
                                    cc.eventManager.removeListener(listener);
                                    that.loadGame();
                                } else {
                                    var str = '检查更新失败, 正在等待重试';
                                    progressLabel.setString(str);
                                    if (--retainCnt >= 0)
                                        manager.release();
                                    cc.eventManager.removeListener(listener);
                                    setTimeout(function () {
                                        var scene = new UpdateScene();
                                        scene.run();
                                    }, 2000);
                                }
                                break;
                            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
                            case jsb.EventAssetsManager.UPDATE_FINISHED:
                                cc.log("Update finished.");
                                if (cc.sys.isObjectValid(manager)) {
                                    if (manager.getLocalManifest().getVersion())
                                        window.curVersion = manager.getLocalManifest().getVersion();

                                    if (--retainCnt >= 0)
                                        manager.release();
                                }
                                that.loadGame();
                                break;
                            case jsb.EventAssetsManager.UPDATE_FAILED:
                                cc.log("Update failed. " + event.getMessage());
                                if (cc.sys.isObjectValid(manager)) {
                                    manager.downloadFailedAssets();
                                }
                                break;
                            case jsb.EventAssetsManager.ERROR_UPDATING:
                                var str = '检查更新失败, 请检查您的网络并尝试重启游戏';
                                progressLabel.setString(str);
                                // alert1(str);
                                if (cc.sys.isObjectValid(manager)) {
                                    if (--retainCnt >= 0)
                                        manager.release();
                                }
                                that.loadGame();
                                // cc.log("Asset update error: " + event.getAssetId() + ", " + event.getMessage());
                                break;
                            case jsb.EventAssetsManager.ERROR_DECOMPRESS:
                                var str = '检查更新失败, 请检查您的网络并尝试重启游戏';
                                progressLabel.setString(str);
                                // alert1(str);
                                if (cc.sys.isObjectValid(manager)) {
                                    if (--retainCnt >= 0)
                                        manager.release();
                                }
                                that.loadGame();
                                // cc.log(event.getMessage());
                                break;
                            default:
                                break;
                        }
                    });
                }

                cc.eventManager.addListener(listener, 1);
                cc.director.runScene(this);
            }
            else {
                this.loadGame();
            }

            return true;
        },
        loadGame: function () {
            cc.loader.loadJs(["src/_files_.js"], function (err) {
                cc.loader.loadJs(jsFiles, function (err) {
                    cc.director.runScene(new LoginScene());
                });
            });
        }
    });

    exports.UpdateScene = UpdateScene;
})(window);
